package newui.page;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.common.ui.dialog.CustomAlertDialog;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.main.adapter.ContactsAdapter;
import com.netease.nim.demo.main.fragment.MainTabFragment;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nim.demo.session.model.MsgListItem;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.ImageAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.NewInteractionCreateTeamChMActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.ContactInfo;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.FileUtil;
import logic.util.Utils;
import newui.bean.TopTeam;

/**
 * Created by lex on 2017/7/19.
 */

public class GroupPage
        extends
        AbstractUIPage<MainActivity> {
    private static final String TAG = "GroupPage";

    public static GroupPage instance;

    public static GroupPage getInstance(MainActivity bActivity) {
        if (instance == null) {
            instance = new GroupPage(bActivity);
        } else {
            instance.setActivity(bActivity);
        }
        return instance;
    }

    public GroupPage(MainActivity t) {
        super(t);
    }


    private Context context;

    /**
     * 页面类型 : 1为客户经理，2为普通用户
     */
    private int pageType = 1;
    private ListView contactsListView;
    private List<Object> items = new ArrayList<>();
    private ContactsAdapter mAdapter;
    private View emptyBg;

    private View notifyBar;

    private TextView tvTitle;
    private Button btnBack, btnCreateTeam;

    private boolean msgLoaded = false;
    private boolean isMangerLoadOk = true;
    private boolean isTeamLoadOk = false;
    public static int currentPosition;
    private Handler handler = new Handler();

    private String fromType;
    private MsgListItem selectedItem = null;
    private File file = null;
    private String teamId = "";
    private TextView tvCreateTeam;

    //    群组置顶信息保存到本地
    private SharedPreferences sp = null;
    private boolean isCurTeamTop = false;
    private Gson gson = null;

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //			                                           Bundle bundle = msg.getData();
            switch (msg.what) {
                case 1:
                    //															   String accId = bundle.getString("id");
                    IMMessage message = MessageBuilder.createImageMessage(teamId, SessionTypeEnum.Team, file, null);
                    NIMClient.getService(MsgService.class).sendMessage(message, false);
                    Toast.makeText(context, "转发成功", Toast.LENGTH_LONG).show();
                    break;
                case -1:
                    Toast.makeText(context, "转发失败", Toast.LENGTH_LONG).show();
                default:
                    break;
            }
        }

    };

    private RelativeLayout layoutTitle;

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.new_i_contacts_frament, null);
        fromType = "contactList";
//        selectedItem = (MsgListItem) getIntent().getSerializableExtra("message");
        initViews();
        setListeners();
        getPageType();
        //		getContactsList();
        requestContacts(false);
        initContactsList();
        registerObservers(true);
        return curMyView;
    }

    private void registerObservers(boolean register) {
        registerTeamUpdateObserver(register);
    }

    /**
     * 注册群信息&群成员更新监听
     */
    private void registerTeamUpdateObserver(boolean register) {
        if (register) {
            TeamDataCache.getInstance().registerTeamDataChangedObserver(teamDataChangedObserver);
        } else {
            TeamDataCache.getInstance().unregisterTeamDataChangedObserver(teamDataChangedObserver);
        }
    }

    TeamDataCache.TeamDataChangedObserver teamDataChangedObserver = new TeamDataCache.TeamDataChangedObserver() {

        @Override
        public void onUpdateTeams(List<Team> teams) {
        }

        @Override
        public void onRemoveTeam(Team team) {
            //TODO  解散群
            for (Object item : items) {
                if (item instanceof Team) {
                    Team temp = (Team) item;
                    if (TextUtils.equals(temp.getId(), team.getId())) {
                        items.remove(item);
                        mAdapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
        }
    };

    private void initViews() {
        tvCreateTeam = (TextView) curMyView.findViewById(R.id.common_header_create_team);
        contactsListView = (ListView) curMyView.findViewById(R.id.new_i_contacts_lv);
        notifyBar = curMyView.findViewById(R.id.status_notify_bar);
        emptyBg = curMyView.findViewById(R.id.new_i_contacts_empty_rlay);
        notifyBar.setVisibility(View.GONE);
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText("群组");
        btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.GONE);
        btnCreateTeam = (Button) curMyView.findViewById(R.id.common_header_commit);
        tvCreateTeam.setText("创建");
        tvCreateTeam.setVisibility(View.VISIBLE);
        layoutTitle = (RelativeLayout) curMyView.findViewById(R.id.layoutTitle);
        layoutTitle.setVisibility(View.GONE);

        //长按监听，置顶功能
//        contactsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                if (position < contactsListView.getHeaderViewsCount()) {
//                    return false;
//                }
//                showLongClickMenu((Team) parent.getAdapter().getItem(position));
//                return true;
//            }
//        });

        sp = bActivity.getSharedPreferences("topTeam", Context.MODE_PRIVATE);
    }

    private void showLongClickMenu(final Team team) {
        gson = new Gson();
        List<TopTeam> allList = new ArrayList<>();
        List<TopTeam> tList = null;
        final TopTeam topTeam = new TopTeam();
        topTeam.setTeamName(team.getName());
        topTeam.setTeamId(team.getId());
        topTeam.setCreateTime(team.getCreateTime());
        final CustomAlertDialog alertDialog = new CustomAlertDialog(bActivity);
        alertDialog.setTitle(team.getName());
        final String cur_account = UserDao.getInstance(bActivity).getLastLoginUser().getAccount();
        final String jsonStr = sp.getString(cur_account, "");
        String title = "";
        if (null == jsonStr || jsonStr == "") {
            isCurTeamTop = false;
            title = "置顶该群组";
            tList = new ArrayList<>();
        }
        if (null != jsonStr && jsonStr.length() != 0) {
            tList = gson.fromJson(jsonStr, new TypeToken<List<TopTeam>>() {
            }.getType());
            for (int m = 0; m < items.size(); m++) {
                Team team1 = (Team) items.get(m);
                TopTeam topTeam1 = new TopTeam();
                topTeam1.setTeamName(team1.getName());
                topTeam1.setCreateTime(team1.getCreateTime());
                topTeam1.setTeamId(team1.getId());
                allList.add(topTeam1);
            }
            for (int i = 0; i < tList.size(); i++) {
                if (!allList.contains(tList.get(i))) {
                    tList.remove(i);//如果有的群解散了，这里本地存储的移除
                }
            }
            if (tList.contains(topTeam)) {
                isCurTeamTop = true;
                title = "取消置顶";
            } else {
                isCurTeamTop = false;
                title = "置顶该群组";
            }
        }
        final List<TopTeam> finalTList = tList;
        alertDialog.addItem(title, new CustomAlertDialog.onSeparateItemClickListener() {
            @Override
            public void onClick() {
                if (isCurTeamTop) {
                    finalTList.remove(topTeam);
                } else {
                    finalTList.add(topTeam);
                }
                Collections.sort(finalTList, new ComparatorTopTeam());
                mAdapter.setTopNum(finalTList.size());
                for (int i = 0; i < items.size() - 1; i++) {
                    for (int j = 1; j < items.size() - i; j++) {
                        Team a = null;
                        Team b = null;
                        if (items.get(j - 1) instanceof Team) {
                            a = (Team) items.get(j - 1);
                        }
                        if (items.get(j) instanceof Team) {
                            b = (Team) items.get(j);
                        }
                        if (a.getCreateTime() < b.getCreateTime()) {
                            items.set((j - 1), items.get(j));
                            items.set(j, a);
                        }
                    }
                }
                for (int n = finalTList.size(); n > 0; n--) {
                    for (int i = 0; i < items.size(); i++) {
                        if (finalTList.get(n - 1).getTeamId().equals(((Team) items.get(i)).getId())) {
                            items.add(0, items.remove(i));
                        }
                    }
                }
                notifyDataSetChanged();
                String json_topteam = gson.toJson(finalTList);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString(cur_account, json_topteam);
                editor.commit();
            }
        });
        title = "取消";
        alertDialog.addItem(title, new CustomAlertDialog.onSeparateItemClickListener() {
            @Override
            public void onClick() {
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
    }

    public class ComparatorTopTeam implements Comparator {
        int flag = -100;

        public int compare(Object obj0, Object obj1) {
            TopTeam topTeam0 = (TopTeam) obj0;
            TopTeam topTeam1 = (TopTeam) obj1;
            if (topTeam0.getCreateTime() > topTeam1.getCreateTime()) {
                flag = 1;
            } else if (topTeam0.getCreateTime() == topTeam1.getCreateTime()) {
                flag = -1;
            } else {
                flag = 0;
            }
            if (flag == 0) {
                return topTeam0.getTeamName().compareTo(topTeam1.getTeamName());
            } else {
                return flag;
            }
        }

    }


    private void setListeners() {
        tvCreateTeam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建群组
                Intent creatTeamIntent = new Intent(bActivity, NewInteractionCreateTeamChMActivity.class);
                creatTeamIntent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_CREATE_TEAM);
                bActivity.startActivityForResult(creatTeamIntent, MainTabFragment.CREATE_TEAM);
            }
        });
    }

    /**
     * 加载群列表
     */
    //	private void getContactsList() {
    //		if (pageType == 0)
    //		{
    //			requestContacts(false);
    //			//			emptyBg.setVisibility(View.VISIBLE);
    //		}
    //		else if (pageType == 1)
    //		{
    //			requestContacts(false);
    //		}
    //		else if (pageType == 2)
    //		{
    //			//			if (null == Const.contactInfo) getUserManger();
    //			requestContacts(false);
    //		}
    //
    //	}
    private void initContactsList() {

        mAdapter = new ContactsAdapter(bActivity, items);
        contactsListView.setAdapter(mAdapter);
        contactsListView.setItemsCanFocus(true);
        contactsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentPosition = position;
                Object obj = parent.getAdapter().getItem(position);
                talkto(obj);
            }
        });

    }

    private void requestContacts(boolean delay) {

        getHandler().postDelayed(new Runnable() {

            @Override
            public void run() {
                NIMClient.getService(TeamService.class).queryTeamList().setCallback(new RequestCallback<List<Team>>() {

                    @Override
                    public void onException(Throwable arg0) {
                        Logger.e(arg0);
                        isTeamLoadOk = false;
                    }

                    @Override
                    public void onFailed(int arg0) {
                        Logger.i("failed");
                        isTeamLoadOk = true;
                    }

                    @Override
                    public void onSuccess(List<Team> arg0) {
                        Logger.d("success");
                        isTeamLoadOk = true;
                        if (items != null && items.size() > 0)
                            items.clear();
                        if (arg0 != null) {
                            items.addAll(arg0);
                            if (null != Const.contactInfo)
                                items.add(0, Const.contactInfo);
                        }
                        for (int i = 0; i < items.size() - 1; i++) {
                            for (int j = 1; j < items.size() - i; j++) {
                                Team a = null;
                                Team b = null;
                                if (items.get(j - 1) instanceof Team) {
                                    a = (Team) items.get(j - 1);
                                }
                                if (items.get(j) instanceof Team) {
                                    b = (Team) items.get(j);
                                }
                                if (a.getCreateTime() < b.getCreateTime()) { // 比较两个整数的大小
                                    items.set((j - 1), items.get(j));
                                    items.set(j, a);
                                }
                            }
                        }
                        String cur_account = UserDao.getInstance(bActivity).getLastLoginUser().getAccount();
                        String jsonStr = sp.getString(cur_account, "");
                        List<TopTeam> allList = new ArrayList<>();
                        List<TopTeam> tList = new ArrayList<>();
                        gson = new Gson();
                        if (null != jsonStr && jsonStr.length() != 0) {
                            tList = gson.fromJson(jsonStr, new TypeToken<List<TopTeam>>() {
                            }.getType());
                            for (int m = 0; m < items.size(); m++) {
                                Team team1 = (Team) items.get(m);
                                TopTeam topTeam1 = new TopTeam();
                                topTeam1.setTeamName(team1.getName());
                                topTeam1.setCreateTime(team1.getCreateTime());
                                topTeam1.setTeamId(team1.getId());
                                allList.add(topTeam1);
                            }
                            for (int i = 0; i < tList.size(); i++) {
                                if (!allList.contains(tList.get(i))) {
                                    tList.remove(i);//如果有的群解散了，这里本地存储的移除
                                }
                            }
                        }
                        Collections.sort(tList, new ComparatorTopTeam());
                        mAdapter.setTopNum(tList.size());
                        for (int n = tList.size(); n > 0; n--) {
                            for (int i = 0; i < items.size(); i++) {
                                if (tList.get(n - 1).getTeamId() == ((Team) items.get(i)).getId()) {
                                    items.add(0, items.remove(i));
                                }
                            }
                        }
                        notifyDataSetChanged();
                        String json_topteam = gson.toJson(tList);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString(cur_account, json_topteam);
                        editor.commit();

                        notifyDataSetChanged();
                        //						if (pageType == 2 && isMangerLoadOk)
                        //						{
                        //						}
                        //						else if (pageType == 1)
                        //						{
                        //							notifyDataSetChanged();
                        //						}
                    }
                });
            }
        }, delay ? 250 : 0);

    }

    private Handler getHandler() {
        return handler;
    }

    private void postRunnable(final Runnable runnable) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                // validate
                // TODO use getActivity ?
                //				if (!isAdded()) { return; }

                // run
                runnable.run();
            }
        });
    }

    private void postDelayed(final Runnable runnable, long delay) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // validate
                // TODO use getActivity ?
                //				if (!isAdded()) { return; }

                // run
                runnable.run();
            }
        }, delay);
    }

    private void notifyDataSetChanged() {

        boolean empty = items.isEmpty();
        emptyBg.setVisibility(empty ? View.VISIBLE : View.GONE);
        mAdapter.notifyDataSetChanged();
    }

    private void getPageType() {
        if (Const.UserRole.equals("0")) {
            pageType = 0;
        } else if (Const.UserRole.equals("1")) {
            pageType = 1;
        } else if (Const.UserRole.equals("2")) {
            pageType = 2;
        }
    }

    /**
     * 获取客户的客户经理信息
     */
    private void getUserManger() {
        NewActionHelp.qryMyBoss(context, new GetUserMangerHandler());
    }

    class GetUserMangerHandler
            extends
            ObjectHttpResponseHandler<ContactInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            isMangerLoadOk = false;
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, ContactInfo object, String responseString) {
            isMangerLoadOk = true;
            if (object != null) {
                items.add(0, object);
                Const.contactInfo = object;
                if (isTeamLoadOk)
                    notifyDataSetChanged();
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<ContactInfo>() {
            }.getType();
        }

    }

    /**
     * 跳转到聊天页面
     *
     * @param item
     */
    protected void talkto(Object item) {
        if (item instanceof ContactInfo) {
            ContactInfo info = (ContactInfo) item;
            String str;
            if (Utils.isEmpty(info.getNickName())) {
                str = info.getAccount();
            } else {
                str = info.getNickName();
            }
            //			Intent intent = new Intent();
            //			intent.putExtra(DefaultConsts.TO_P2P_PAGE_TAG, DefaultConsts.TO_P2P_PAGE_FROM_CONTACT_MANGER);
            //			intent.putExtra(DefaultConsts.TO_P2P_PAGE_INFO, str);
            //			P2PMessageActivity.start(getActivity(), info.getAccId(), intent);
            P2PMessageActivity.start(bActivity, info.getAccId(), str);
            //			startActivity(new Intent(getActivity(), P2PMessageActivity.class));
        } else if (item instanceof Team) {
            Team team = (Team) item;
            if (fromType.equals("forward")) {
                ImageAttachment attachment = (ImageAttachment) selectedItem.getMessage().getAttachment();
                if (Utils.isNotEmpty(attachment.getUrl())) {
                    file = downUrlTxt(attachment.getUrl(), FileUtil.ImageSavePath());
                } else {
                    file = downUrlTxt(attachment.getPath(), FileUtil.ImageSavePath());
                }
                teamId = team.getId();
//                        finish();
            } else {
                TeamMessageActivity.start(bActivity, team.getId());
            }
        }

    }

    public File downUrlTxt(final String fileUrl, String downPath) {
        final File savePath = new File(downPath);

        if (!savePath.exists()) {
            savePath.mkdir();
        }
        String[] urlname = fileUrl.split("/");
        int len = urlname.length - 1;
        final String uname = urlname[len];//获取文件名
        final File file1 = new File(savePath + "/" + uname + ".png");//创建新文件  ;
        new Thread() {
            @Override
            public void run() {
                try {
                    //					file = new File(savePath + "/" + uname + ".png");//创建新文件
                    if (file1 != null && !file1.exists()) {
                        file1.createNewFile();
                    }
                    OutputStream oputstream = new FileOutputStream(file1);
                    URL url = new URL(fileUrl);
                    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
                    uc.setRequestMethod("GET");
                    uc.setConnectTimeout(5 * 1000);
                    uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true
                    uc.connect();
                    InputStream iputstream = uc.getInputStream();
                    //			System.out.println("file size is:" + uc.getContentLength());//打印文件长度
                    byte[] buffer = new byte[4 * 1024];
                    int byteRead = -1;
                    while ((byteRead = (iputstream.read(buffer))) != -1) {
                        oputstream.write(buffer, 0, byteRead);
                    }
                    oputstream.flush();
                    iputstream.close();
                    oputstream.close();
                    Message msg = Message.obtain();
                    msg.what = 1;
                    myHandler.sendMessage(msg);
                } catch (Exception e) {
                    System.out.println("读取失败！");
                    Message msg = Message.obtain();
                    msg.what = -1;
                    myHandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        }.start();

        return file1;
    }


    @Override
    public void dispose() {
        super.dispose();
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        requestContacts(false);
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        registerObservers(false);
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case DefaultConsts.CREATE_TEAM:
                requestContacts(false);
                break;
        }
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }


    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }
}
